<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--仓库查询数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="商品编号" prop="productCode">
            <el-input
              v-model="queryParams.productCode"
              placeholder="请输入商品编号"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="商品名称" prop="productName">
            <el-input
              v-model="queryParams.productName"
              placeholder="请输入商品名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="类型" prop="productType">
            <el-select
              v-model="queryParams.productType"
              placeholder="类型"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in typeList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['wms:product:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['wms:product:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['wms:product:export']"
            >导出</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="dataList" >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="商品编号" align="center" key="productCode" prop="productCode" />
          <el-table-column label="商品名称" align="center" key="productName" prop="productName"/>
          <el-table-column label="规格" align="center" key="specUnit">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_product_unit" :value="scope.row.specUnit"/>
            </template>
          </el-table-column>
          <el-table-column label="商品类型" align="center" key="productType">
            <template slot-scope="scope">
              <dict-tag :options="typeList" :value="scope.row.productType"/>
            </template>
          </el-table-column>
          <el-table-column label="存储单位" align="center" key="productUnit">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_product_unit" :value="scope.row.productUnit"/>
            </template>
          </el-table-column>
          <el-table-column label="预警(下)" align="center" key="minStock" prop="minStock"/>
          <el-table-column label="预警(上)" align="center" key="maxStock" prop="maxStock"/>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['wms:product:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['wms:product:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 导入对话框   -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品编号" prop="productCode">
              <el-input v-model="form.productCode" placeholder="请输入商品编号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入商品名称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品类型" prop="productType">
              <el-select v-model="form.productType" placeholder="请选择商品类型" clearable>
                <el-option
                  v-for="dict in typeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="specUnit">
              <el-select v-model="form.specUnit" placeholder="请选择规格" clearable>
                <el-option
                  v-for="dict in dict.type.wms_product_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预警(下)" prop="minStock">
              <el-input v-model="form.minStock" placeholder="请输入预警(下)" type="number" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预警(上)" prop="maxStock">
              <el-input v-model="form.maxStock" placeholder="请输入预警(上)" type="number" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="存储单位" prop="productUnit">
            <el-select v-model="form.productUnit" placeholder="请选择存储单位" clearable>
              <el-option
                v-for="dict in dict.type.wms_product_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addObj, delObj, editObj, findAllList, findById } from "@/api/wms/product";
import { getDictInfo } from "@/api/wms/productType";
import {getToken} from "@/utils/auth";
import { range,checkInt }from "@/utils/ruoyi"
export default {
  name: "Product",
  dicts: ['wms_product_unit'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据列表
      dataList: [],
      // 日期范围
      dateRange: [],
      // 类型列表
      typeList: [],
      // 数据导入
      upload: {
        // 是否显示弹出层（数据导入）
        open: false,
        // 弹出层标题（数据导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据导入
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/wmsProductInfo/importData"
      },
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: undefined,
        productName: undefined,
        productType: undefined
      },
      // 表单校验
      rules: {
        productType: [
          { required: true, message: "商品类型不能为空", trigger: "blur" },
          { required: true, message: "商品类型不能为空", trigger: "change" }
        ],
        productCode: [
          { required: true, message: "商品编号不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '商品编号必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
          { min: 2, max: 50, message: '商品名称必须介于 2 和 50 之间', trigger: 'blur' }
        ],
        productUnit: [
          { required: true, message: "存储单位不能为空", trigger: ['change'] },
        ],
        specUnit: [
          { required: true, message: "规格不能为空", trigger: ['change'] },
        ],
        minStock: [
          range(999999,1,'预警(下)必须介于 1和9999之间'),
          checkInt()
        ],
        maxStock: [
          range(999999,1,'预警(上)必须介于 1和9999之间'),
          checkInt()
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getProductTypeList();
  },
  methods: {
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wmsProductInfo/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "产品导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('wmsProductInfo/importTemplate', {
      }, `product_template_${new Date().getTime()}.xlsx`)
    },
    getProductTypeList(){
      getDictInfo().then(response => {
          this.typeList = response.data;
        }
      );
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      findAllList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        productCode: undefined,
        productName: undefined,
        productType: undefined,
        productUnit: undefined,
        specUnit: undefined,
        minStock: undefined,
        maxStock: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      findById(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            editObj(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addObj(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除商品为"' + row.productCode + '"的数据项？').then(function() {
        return delObj(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
